package com.fengyuncx.tp.ali_push.utils;

import android.annotation.TargetApi;
import android.app.AppOpsManager;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.graphics.Color;
import android.os.Build;

import androidx.core.app.NotificationManagerCompat;

import com.fengyuncx.tp.ali_push.Dlog;

import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class NotificationUtil {
    //与推送channel同步
    public static final String CHANNEL_MAIN_ID = "1";
    public static final String CHANNEL_MAIN_NAME = "消息通知";
    public static final String CHANNEL_MAIN_DESCRIPTION = "平台发送的系统消息和新订单消息将通过此渠道接收";


    public static final String CHANNEL_OFFLINE_ID = "fy_offline";
    public static final String CHANNEL_OFFLINE_NAME = "本地消息";
    private WeakReference<Context> mContext;
    private NotificationManager mManager;
    private NotificationManagerCompat mManagerCompat;

    private LinkedList<HashMap<String, Object>> mNotifications;
    private AtomicInteger mPos; // 0

    private static NotificationUtil instance;
    public static void init(Context context){
        getInstance(context);
    }
    public static NotificationUtil getInstance(Context context) {
        if (instance == null) {
            synchronized (NotificationUtil.class) {
                if (instance == null) {
                    instance = new NotificationUtil(context);
                }
            }
        }
        return instance;
    }

    public boolean isNotificationEnable() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            return mManager.areNotificationsEnabled();
        }else if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.N){
            return mManagerCompat.areNotificationsEnabled();
        } else if (Build.VERSION.SDK_INT >= 19) {
            String CHECK_OP_NO_THROW = "checkOpNoThrow";
            String OP_POST_NOTIFICATION = "OP_POST_NOTIFICATION";
            AppOpsManager appOps =
                    (AppOpsManager) mContext.get().getSystemService(Context.APP_OPS_SERVICE);
            ApplicationInfo appInfo = mContext.get().getApplicationInfo();
            String pkg = mContext.get().getApplicationContext().getPackageName();
            int uid = appInfo.uid;
            try {
                Class<?> appOpsClass = Class.forName(AppOpsManager.class.getName());
                Method checkOpNoThrowMethod = appOpsClass.getMethod(CHECK_OP_NO_THROW, Integer.TYPE,
                        Integer.TYPE, String.class);
                Field opPostNotificationValue = appOpsClass.getDeclaredField(OP_POST_NOTIFICATION);
                int value = (int) opPostNotificationValue.get(Integer.class);
                return ((int) checkOpNoThrowMethod.invoke(appOps, value, uid, pkg)
                        == AppOpsManager.MODE_ALLOWED);
            } catch (ClassNotFoundException | NoSuchMethodException | NoSuchFieldException
                    | InvocationTargetException | IllegalAccessException | RuntimeException e) {
                return true;
            }
        } else {
            return true;
        }
    }
    private NotificationUtil(Context context) {
        mContext = new WeakReference<>(context);
        mNotifications = new LinkedList<HashMap<String, Object>>();
        mPos = new AtomicInteger(0);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            mManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            createDefaultChannels();
        } else {
            mManagerCompat = NotificationManagerCompat.from(context);
        }
    }

    private final String TAG = this.getClass().getSimpleName();
    @TargetApi(Build.VERSION_CODES.O)
    public void createDefaultChannels(){
        NotificationChannel mainChannel = null;
        if(mManager == null){
            return;
        }
        List<NotificationChannel> channelList = new ArrayList<>();
        mainChannel = mManager.getNotificationChannel(CHANNEL_MAIN_ID);
        if(mainChannel == null) {
            mainChannel = new NotificationChannel(CHANNEL_MAIN_ID, CHANNEL_MAIN_NAME, NotificationManager.IMPORTANCE_HIGH);
            // 配置通知渠道的属性
            mainChannel.setDescription(CHANNEL_MAIN_DESCRIPTION);
            // 设置通知出现时的闪灯（如果 android 设备支持的话）
            mainChannel.enableLights(true);
            mainChannel.setLightColor(Color.RED);
            // 设置通知出现时的震动（如果 android 设备支持的话）
            mainChannel.enableVibration(true);
            mainChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
            channelList.add(mainChannel);
        }
        Dlog.e(TAG,  "---mainChannel:"+mainChannel.toString());
        if(channelList != null && channelList.size() > 0){
            mManager.createNotificationChannels(channelList);
        }
    }


}
